<?php
/**
 * This file is supply ulti or common Component
 */

/**
 * @return mixed|string
 */
function atom_custom_logo()
{
    $custom_logo_id = get_theme_mod('custom_logo');
    $logo = wp_get_attachment_image_src($custom_logo_id, 'full');
    $logo_url = has_custom_logo() ? $logo[0] : get_theme_file_uri('assets/image/logo.png');
    return $logo_url;
}

function atom_breadcrumb() {
	$start_el = '<nav aria-label="breadcrumb"><ol class="breadcrumb bg-transparent d-flex justify-content-center">';
	$title = '<h3 class="text-white h2">'.get_the_title() .'</h3>';
	$item = '<li class="breadcrumb-item"><a href="'.home_url() .'"><i class="fa fa-home mr-1"></i>Home</a></li>';
	if (is_page()) {
		$item .= '<li class="breadcrumb-item active" aria-current="page">'.get_the_title().'</li>';
	}
	if (is_category()) {
		$cid = get_query_var('cat');
		$title = '<h3 class="text-white h2">' . get_category($cid)->name . '</h3>';
		$item .= '<li class="breadcrumb-item active" aria-current="page">'. get_category($cid)->name.'</li>';
	}
	if (is_single()) {
		global $post;
		$post_type = get_post_type();

		if ($post_type !== "post") {
            $item .= '<li class="breadcrumb-item active" aria-current="page">'. $post_type.'</li>';
        }else {
            $cat = get_category($post->post_category[0]);
            $cat_link = get_category_link($cat->term_id);
            $item .= '<li class="breadcrumb-item" aria-current="page"><a href="'.$cat_link .'">'. $cat->name .'</a></li>';
        }

		$item .= '<li class="breadcrumb-item active" aria-current="page">'. get_the_title().'</li>';
	}
	if (is_tax()) {

		$tax = single_term_title('',false);

		$item .= '<li class="breadcrumb-item" aria-current="page">'. $tax .'</li>';
	}
	$end_el = '</ol></nav>';

	return $title. $start_el. $item . $end_el;

}
/*
 * 设置Pagination wrapper.
 * */
function atom_pagination($args = array(), $class = 'posts-navigation', $screen_reader_text = '')
{
	$template = '
	<nav class="navigation pagination justify-content-center atom_pagination" aria-label="Page navigation" role="navigation">
	<ul class="pagination">%3$s</ul>
	</nav>';
	$args = wp_parse_args($args, array(
		'mid_size' => 5,
		'prev_text' => _x('上一页', 'previous set of posts'),
		'next_text' => _x('下一页', 'next set of posts'),
		'screen_reader_text' => __('Posts navigation'),
		'aria_current' => "page",
	));

	$links = paginate_links($args);
	$template = apply_filters('navigation_markup_template', $template, $class);
	echo sprintf($template, sanitize_html_class($class), esc_html($screen_reader_text), $links);
}

//文章的阅读次数
function atom_views($before = '阅读 ', $after = ' 次', $echo = 1)
{
	global $post;
	$post_ID = $post->ID;
	$views = (int)get_post_meta($post_ID, 'views', true);
	if ($echo) echo $before, number_format($views), $after;
	else return $views;
}

function record_visitors()
{
	if (is_singular()) {
		global $post;
		$post_ID = $post->ID;
		if ($post_ID) {
			$post_views = (int)get_post_meta($post_ID, 'views', true);
			if (!update_post_meta($post_ID, 'views', ($post_views + 1))) {
				add_post_meta($post_ID, 'views', 1, true);
			}
		}
	}
}

add_action('wp_head', 'record_visitors');

function atom_get_product() {
	if (isset($_POST['cat'])) {
		$cat = $_POST['cat'] !== "false" ? $_POST['cat'] : [];
	}else {
		$cat = [];
	}
	$arg = [
		'limit' => 12,
		'page' => 1,
		'category'=> $cat,
        'status' => 'publish'
	];
	$products = wc_get_products($arg);
	$output = "<h2 class='text-center'>没有数据</h2>";
	if (count($products)) {
		ob_start();
		foreach ($products as $p) {
			$name = $p->get_name();
			$img = wp_get_attachment_url($p->get_image_id());
			$link = get_post_permalink($p->get_id());
			$price = wc_price($p->price);
			?>
			<div class="col-md-3 mb-4 px-1">
			<article class="portfolio-item">
				<div class="card border-0">
					<figure class="imagebox position-relative">
						<img src="<?php echo $img ?>" class="card-img-top rounded-0" alt="<?php echo $name; ?>">
						<div class="links d-flex justify-content-center">
							<a href="<?php echo $img ?>" class="light_box" data-imagelightbox="f" title="<?php echo $name; ?>" data-ilb2-caption="<?php echo $name; ?>"><i class="fa fa-picture-o"></i></a>
							<a href="<?php echo $link; ?>" title="<?php echo $name;?>"><i class="fa fa-link"></i></a>
						</div>
						<div class="bg-accent position-absolute w-100 h-100"></div>
					</figure>
					<div class="card-body">
						<a class="card-title" href="<?php echo $link;?>">
							<h5 class="text-truncate text-center" title="<?php echo $name; ?>"><?php echo $name; echo $price;?></h5>
						</a>
						<p class="text-center"><small class="text-muted"><i class="fa fa-folder mr-1"></i><?php echo wc_get_product_category_list($p->get_id()); ?></small></p>
					</div>
				</div>
			</article>
			</div><?php
		}
		$output = ob_get_contents();
		ob_end_clean();
	}

	wp_send_json(['code'=>1,'data'=>$output],'200');
	wp_die();
}

add_action("wp_ajax_get_product","atom_get_product");
add_action("wp_ajax_nopriv_get_product","atom_get_product");

/**
 * Add Portfolio post type
 * @date 2019-10-30
 */

add_action('init', 'Atom_custom_post_type');
function Atom_custom_post_type()
{
	$labels = array(
		'name' => _x('Portfolio', 'post type general name','wdstar'),
		'singular_name' => _x('Portfolio', 'post type singular name','wdstar'),
		'add_new' => _x('添加', 'Portfolio','wdstar'),
		'add_new_item' => __('Add New Portfolio','wdstar'),
		'edit_item' => __('Edit Portfolio','wdstar'),
		'new_item' => __('New Portfolio','wdstar'),
		'view_item' => __('View Portfolio',"wdstar"),
		'search_items' => __('Search Portfolio' ,"wdstar"),
		'not_found' =>  __('No Portfolio found' ,"wdstar"),
		'not_found_in_trash' => __('No Portfolio found in Trash' ,"wdstar"),
		'parent_item_colon' => '',
		'menu_name' => '作品'

	);
	$args = array(
		'labels' => $labels,
		'public' => true,
		'publicly_queryable' => true,
		'show_ui' => true,
		'show_in_menu' => true,
		'query_var' => true,
		'rewrite' => true,
		'capability_type' => 'post',
		'has_archive' => true,
		'hierarchical' => false,
		'menu_position' => null,
		'supports' => array('title','editor','author','thumbnail','revisions')
	);
	register_post_type('portfolio',$args);

	//为portfolio添加分类
	register_taxonomy('genre',array('portfolio'), array(
		'hierarchical' => true,//true为分类，false为标签
	));
}

//添加过滤器，以确保课本用户更新时会显示。
add_filter('post_updated_messages', 'portfolio_updated_messages');
function portfolio_updated_messages( $messages ) {
	global $post, $post_ID;

	$messages['portfolio'] = array(
		0 => '', // 未使用。信息开始在索引1。
		1 => sprintf( __('portfolio updated. <a href="%s">View portfolio</a>'), esc_url( get_permalink($post_ID) ) ),
		2 => __('Custom field updated.'),
		3 => __('Custom field deleted.'),
		4 => __('portfolio updated.'),
		/* translators: %s: date and time of the revision */
		5 => isset($_GET['revision']) ? sprintf( __('portfolio restored to revision from %s'), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
		6 => sprintf( __('portfolio published. <a href="%s">View portfolio</a>'), esc_url( get_permalink($post_ID) ) ),
		7 => __('portfolio saved.'),
		8 => sprintf( __('portfolio submitted. <a target="_blank" href="%s">Preview portfolio</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
		9 => sprintf( __('portfolio scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview portfolio</a>'),
			// translators: Publish box date format, see http://php.net/date
			date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( get_permalink($post_ID) ) ),
		10 => sprintf( __('portfolio draft updated. <a target="_blank" href="%s">Preview portfolio</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
	);

	return $messages;
}

//显示图书上下文帮助
add_action( 'contextual_help', 'add_help_text', 10, 3 );

function add_help_text($contextual_help, $screen_id, $screen) {
	//$contextual_help .= var_dump($screen); // use this to help determine $screen->id
	if ('portfolio' == $screen->id ) {
		$contextual_help =
			'<p>' . __('Things to remember when adding or editing a portfolio:') . '</p>' .
			'<ul>' .
			'<li>' . __('Specify the correct genre such as Mystery, or Historic.') . '</li>' .
			'<li>' . __('Specify the correct writer of the portfolio.  Remember that the Author module refers to you, the author of this portfolio review.') . '</li>' .
			'</ul>' .
			'<p>' . __('If you want to schedule the portfolio review to be published in the future:') . '</p>' .
			'<ul>' .
			'<li>' . __('Under the Publish module, click on the Edit link next to Publish.') . '</li>' .
			'<li>' . __('Change the date to the date to actual publish this article, then click on Ok.') . '</li>' .
			'</ul>' .
			'<p><strong>' . __('For more information:') . '</strong></p>' .
			'<p>' . __('<a href="http://codex.wordpress.org/Posts_Edit_SubPanel" target="_blank">Edit Posts Documentation</a>') . '</p>' .
			'<p>' . __('<a href="http://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>' ;
	} elseif ( 'edit-portfolio' == $screen->id ) {
		$contextual_help =
			'<p>' . __('This is the help screen displaying the table of Portfolio.') . '</p>' ;
	}
	return $contextual_help;
}

/* WooCommerce Checkout Field*/

add_filter( 'woocommerce_default_address_fields' , 'custom_override_default_address_fields' );

function custom_override_default_address_fields( $address_fields ) {
	unset($address_fields['company']);
	unset($address_fields['postcode']);
	unset($address_fields['address_1']);

     return $address_fields;
}

add_action('woocommerce_template_single_add_to_cart','custom_wc_template_single_add_to_cart');
function custom_wc_template_single_add_to_cart($key, $args) {
    if ($key == "quantity") {
        $args['input_class'] = ['form-control'];
    }
    return $args;
}
